<template>
  <view class="container">
    <!-- 导航 -->
    <custom-nav title="实名认证"></custom-nav>
    <view class="content">
      <image :src="realImg" class="n-icon" />

      <view class="t-title t-color">实名认证的好处</view>

      <view class="t-con"
        >1、资料中会显示<text class="t-color">“已实名”</text
        >图标，增加自身资料的可信度</view
      >
      <view class="t-con"
        >2、同城<text class="t-color">优先被推荐</text
        >提升曝光度，更容易被其他家长看到</view
      >
      <view class="t-con"
        >3、阿里云平台认证，费用<text class="t-color"
          >10元（官方认证手续费）</text
        >，完美繁花不收取额外费用</view
      >
      <view class="t-con"
        >4、填写真实姓名和身份证号进行认证，如<text class="t-color"
          >认证失败可重新填写，不用重复付款</text
        ></view
      >

      <view class="t-form-box">
        <uni-forms>
          <uni-forms-item label="姓名" name="name" class="form-item">
            <uni-easyinput
              trim
              v-model="formData.name"
              :clearable="false"
              @input="formatFn('name')"
              :inputBorder="false"
              :styles="inputStyle"
              placeholderStyle="font-size:36rpx;"
              placeholder="输入姓名"
              cursor-spacing="230"
              :disabled="isConfirm == 2"
            ></uni-easyinput>
          </uni-forms-item>
          <uni-forms-item label="身份证" name="idcard" class="form-item">
            <uni-easyinput
              trim
              v-model="formData.idcard"
              :clearable="false"
              @input="formatFn('idcard')"
              :inputBorder="false"
              :styles="inputStyle"
              placeholderStyle="font-size:36rpx;"
              placeholder="输入身份证号"
              cursor-spacing="150"
              :disabled="isConfirm == 2"
            ></uni-easyinput>
          </uni-forms-item>
        </uni-forms>
        <view
          class="confirm-btn"
          :class="isConfirm == 2 ? 'is-confirm' : ''"
          @click="submitFn"
        >
          <custom-btn>{{ btnText }}</custom-btn>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref } from "vue";
import { realnameApi, realpayApi } from "@/api/my";
import { getItem } from "@/utils/storage";
import { urlConf } from "@/config/resource";

const realImg = urlConf + "common/realname.png";

const formData = reactive({});
const inputStyle = {
  border: "none",
  fontSize: "36rpx",
  height: "140rpx",
  background: "transparent",
};
const isConfirm = ref(null);

const btnText = computed(() => {
  const cObj = {
    0: "立即认证并支付",
    1: "立即认证（无需支付）",
    2: "已认证",
  };
  return cObj[isConfirm.value];
});

// -------------称呼限制两个字符-------------
const formatFn = (t) => {
  const lenObj = {
    name: 5,
    idcard: 18,
  };

  const nameRegex = /[^\u4E00-\u9FA5]/g;
  const idRegex = /[\W]/g;
  const regex = t == "name" ? nameRegex : idRegex;
  nextTick(() => {
    let nWord = formData[t].replace(regex, "");
    formData[t] = nWord.slice(0, lenObj[t]);
  });
};

// 验证输入项
const checkFormat = () => {
  if (!formData.name) {
    uni.showToast({
      title: "请输入姓名",
      icon: "none",
    });
    return false;
  }

  const reg = /^([1-9]\d{5})(\d{4})(\d{2})(\d{2})(\d{3})(\d|X)$/;
  if (!reg.test(formData.idcard)) {
    uni.showToast({
      title: "请输入正确的身份证号码",
      icon: "none",
    });
    return false;
  }

  return true;
};

const submitFn = () => {
  if (isConfirm.value == 2) return;
  if (!checkFormat()) return;
  if (isConfirm.value == 1) {
    realnameFn();
    return;
  }
  const { id } = getItem("user_info") || {};

  realpayApi({ member_id: id }).then((res) => {
    const { payment } = res.data;
    uni.requestPayment({
      signType: "MD5",
      provider: "payment",
      package: payment.prepay_id,
      ...payment,
      success: function (res) {
        realnameFn();
      },
      fail: function (err) {
        let msg = "支付失败，请稍候再试";
        if (err.errMsg.includes("cancel")) {
          msg = "取消支付";
        }
        uni.showToast({
          title: msg,
          icon: "none",
        });
        reject(err);
      },
      complete: function (res) {},
    });
  });
};

// 实名认证接口
const realnameFn = () => {
  realnameApi(formData)
    .then((res) => {
      const { code } = res.data;
      if (code == 400) {
        isConfirm.value = 1;
        uni.showToast({
          title: "实名信息有误，请重新输入",
          icon: "none",
        });
        return;
      }
      if (code == 200) {
        isConfirm.value = 2;
        uni.showToast({
          title: "认证成功",
          icon: "none",
        });
      }
    })
    .catch((err) => {
      isConfirm.value = 1;
      uni.showToast({
        title: "认证失败",
        icon: "none",
      });
      return;
    });
};

function replaceAtIndex(str, minLen, maxLen) {
  return str
    .split("")
    .map((char, idx) => (idx > minLen && idx < maxLen ? "*" : char))
    .join("");
}

onLoad(() => {
  const { realname, name, idcard } = getItem("user_info") || {};
  isConfirm.value = realname;
  if (name && idcard) {
    const nName = replaceAtIndex(name, -1, name.length - 1);
    const nId = replaceAtIndex(idcard, 2, 14);

    formData.name = nName;
    formData.idcard = nId;
  }
});
</script>

<style lang="scss" scoped>
.content {
  background: #fff;
  padding: 30rpx;

  .n-icon {
    width: 100%;
    height: 220rpx;
  }
  .t-color {
    color: #f65952;
    font-weight: 600;
  }
  .t-title {
    font-size: 48rpx;
    font-weight: 800;
    text-align: center;
    padding-top: 40rpx;
    letter-spacing: 1rpx;
    padding-bottom: 10rpx;
  }

  .t-con {
    font-size: 36rpx;
    padding: 15rpx;
    line-height: 56rpx;
    font-weight: 500;
  }

  .form-item {
    background: #f5f5f5;
  }
}
.t-form-box {
  padding-top: 40rpx;
}

::v-deep .uni-forms-item {
  background: #f5f5f5;
  border-radius: 10rpx;
  margin-bottom: 20rpx;
  padding-left: 40rpx;
  font-size: 36rpx;
  display: flex;
  align-items: center;
}
::v-deep .uni-forms-item__label {
  font-size: 36rpx;
  color: #222;
  line-height: 1;
  padding: 0;
}

::v-deep .uni-easyinput__content-input {
  font-size: 36rpx !important;
  text-align: right;
  padding: 40rpx;
}

::v-deep .uni-easyinput__placeholder-class {
  font-size: 36rpx !important;
}
.confirm-btn {
  width: 100%;
  height: 120rpx;
  line-height: 120rpx;
  font-weight: bold;
  font-size: 36rpx;
  color: #fff;
  background: #f65952;
  border-radius: 120rpx;
  margin: 40rpx 0;
}
.is-confirm {
  opacity: 0.5;
}
</style>
